package com.wf.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.wf.constant.RedisConstant;
import com.wf.domain.ContractInfo;
import com.wf.domain.MessageInfo;
import com.wf.domain.User;
import com.wf.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author mpk
 * @since 2024/9/18 10:22:08
 */
@Slf4j
@Service
public class AgencyFailService implements JavaDelegate {


    @Override
    public void execute(DelegateExecution execution) {

        try {

            UserService userService = SpringUtil.getBean(UserService.class);
            RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
            MessageInfoService messageInfoService = SpringUtil.getBean(MessageInfoService.class);

            Map<String, Object> variables = execution.getVariables();
            ContractInfo contractInfo = (ContractInfo) variables.get("contractInfo");
            log.info("contractInfo: {}", contractInfo);

            User user = userService.getById(contractInfo.getUserId());
            // 更新流程变量
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setUserId(user.getUserId());
            messageInfo.setContent("签约失败,请检查信息是否正确！！");
            messageInfo.setTitle("合同通知");
            messageInfoService.save(messageInfo);
            if (StrUtil.isNotEmpty(user.getEmail()))
            {
                variables.put("recipient", user.getEmail());
            }else
            {
                variables.put("recipient", "3038594747@qq.com");
            }
            variables.put("subject", "签约失败！！");
            variables.put("male", true);
            variables.put("now", LocalDateTime.now());
            execution.setVariables(variables);
            log.info("流程执行失败，发送邮件");
            redisUtil.setRemove(RedisConstant.APARTMENT_SIGN_APPLY, contractInfo.getContractId().toString());

        } catch (Exception e) {
            log.error("执行过程中发生异常: ", e);
            // 这里可以选择抛出自定义异常或处理
        }
    }
}
